package person.bing.fbcloud.leetcode;

import java.util.*;

/**
 * 超时了
 * @author: mengfanbing
 * @date: 2020/9/24 9:21
 */

public class Q501 {
    public static void main(String[] args) {

        TreeNode root = new TreeNode(2147483647);

        System.out.println(Arrays.toString(findMode(root)));
    }
    public static int[] findMode(TreeNode root) {
        if (root == null){
            return new int[0];
        }
        util(root);
        Integer maxValue = null;
        if (map.size()>1){
            maxValue = map.values().stream().sorted((x, y) -> y.compareTo(x)).findFirst().get();
        }else {
            maxValue = Integer.parseInt(map.values().toArray()[0].toString());
        }
        List<Integer> temp = new ArrayList<>();
        for (Map.Entry<Integer,Integer> entry :
                map.entrySet()) {
            if (entry.getValue() == maxValue){
                temp.add(entry.getKey());
            }
        }
        int size = temp.size();
        int[] ans = new int[size];
        for (int i=0;i<size;i++){
            ans[i] = temp.get(i);
        }
        return ans;
    }
    public static void util(TreeNode root) {
        if (root == null){
            return;
        }
        int val = root.val;
        Integer value = map.get(val);
        if (value != null){
            map.put(val,value+1);
        }else {
            map.put(val,1);
        }
        util(root.left);
        util(root.right);
    }

    private static Map<Integer,Integer> map = new HashMap<>();
    public static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
    }
}
